package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.widget.tablayout.CommonTabLayout;
import com.epfresh.api.widget.tablayout.TabEntity;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.BaseStoreInfo;
import com.epfresh.supplier.fragment.BaseStoreBaseWebFragment;
import com.epfresh.supplier.fragment.BaseStoreInfoFragment;
import com.epfresh.supplier.fragment.BaseStoreProductFragment;

import java.util.ArrayList;

public class BaseStoreInfoActivity extends BaseActivity implements OnTabSelectListener {

    private CommonTabLayout mlyTab;

    private String mBaseStoreId;
    private boolean mHasAgent;

    private TextView mTvSearch;
    private TextView mTvBaseStoreName;
    private TextView mTvBaseStoreApply;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            getIntent().putExtra("baseStoreId", savedInstanceState.getString("baseStoreId"));
            getIntent().putExtra("mHasAgent", savedInstanceState.getBoolean("mHasAgent",true));
        }
        mBaseStoreId = getIntent().getStringExtra("baseStoreId");
        mHasAgent = getIntent().getBooleanExtra("mHasAgent",true);
        setContentView(R.layout.activity_base_info);
        initView();
        reqBaseStoreInfo();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("baseStoreId", mBaseStoreId);
        outState.putBoolean("mHasAgent",mHasAgent);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        reqBaseStoreInfo();
    }

    @Override
    protected View getToolBar() {
        return null;
    }

    private void initView() {

        mlyTab = (CommonTabLayout) findViewById(R.id.ly_navigation);
        mlyTab.setTabItemRes(R.layout.layout_tab_top);
        mlyTab.setOnTabSelectListener(this);
        mTvSearch = (TextView) findViewById(R.id.tv_search);
        mTvBaseStoreName = (TextView) findViewById(R.id.tv_store_title);
        mTvBaseStoreApply = (TextView) findViewById(R.id.tv_apply);
        mTvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intoSearch();
            }
        });
        mTvBaseStoreApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1申请中，2代办中，3拒绝代办，4暂停代办，其他申请代办
                if (mBaseStoreInfo != null && mBaseStoreInfo.isAgentState()){
                   intoApplyAgent();
                }
            }
        });
        mTvBaseStoreApply.setVisibility(View.GONE);
        mTvBaseStoreName.setVisibility(View.GONE);

        mlyTab.setVisibility(View.GONE);

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    private void intoSearch() {
        if (mBaseStoreId != null && !"".equals(mBaseStoreId)){
            Intent intent = new Intent(this,SearchAcceptActivity.class);
            intent.putExtra("mHasAgent", mHasAgent);
            intent.putExtra("baseStoreId",mBaseStoreId);
            intent.putExtra(Constant.KEY_WEB_URL,com.epfresh.api.constant.Constant.URL_HELP_AGENT_NOTICE);
            startActivity(intent);
        }
    }

    private void intoApplyAgent() {
        SharedPreferences sp = getSharedPreferences("cache_config", Context.MODE_PRIVATE);
        boolean isRead = sp.getBoolean("config_read_agent_notice"+"_"+ ApplicationHelper.getInstance().getUser().getAccountId()+"_"+ BaseApplication.getInstance().getMerchantId(), false);
        if (mBaseStoreId != null && !"".equals(mBaseStoreId)){
            if (!isRead) {
                Intent intent = new Intent(this, WebAgentNoticeActivity.class);
                intent.putExtra("baseStoreId", mBaseStoreId);
                intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_HELP_AGENT_NOTICE);
                startActivity(intent);
            }else {
                Intent intent = new Intent(this,ApplyInfoActivity.class);
                intent.putExtra("baseStoreId",mBaseStoreId);
                startActivityForResult(intent,0x1991);
            }
        }
    }

    private void updateTable(boolean isShowHomePage) {
        String[] mTitles = {"基地首页", "商品",
                "产地信息"
        };
        int[] mIconUnSelectIds = {
                R.mipmap.tab_base_home_unselected,
                R.mipmap.tab_base_goods_unselected,
                R.mipmap.tab_base_info_unselected};
        final int[] mIconSelectIds = {
                R.mipmap.tab_base_home_selected,
                R.mipmap.tab_base_goods_selected,
                R.mipmap.tab_base_info_selected};

        ArrayList<TabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            if (i == 0 && !isShowHomePage) {
                continue;
            }
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        mlyTab.setTabData(mTabEntities);
        mlyTab.setOnTabSelectListener(this);
        typeNav = isShowHomePage ? 1 : 0;
        int currentTab = mlyTab.getCurrentTab();
        if (currentTab < mTabEntities.size()){
            mlyTab.setCurrentTab(currentTab);
            updatePageStatus(currentTab);
        }else {
            mlyTab.setCurrentTab(0);
            updatePageStatus(0);
        }
    }

    //当前选中的tab
    @Override
    public void onTabSelect(int position) {

        updatePageStatus(position);

    }

    //再次点击当前选中的tab
    @Override
    public void onTabReselect(int position) {
    }


    public void updateBaseStoreInfo(BaseStoreInfo baseStoreInfo) {
        mBaseStoreInfo = baseStoreInfo;
        if (baseStoreInfo != null) {
            String homepage = baseStoreInfo.getHomepage();
            if (homepage == null || "".equals(homepage.trim())) {
                updateTable(false);
            } else {
                updateTable(true);

            }

            mTvBaseStoreName.setText(baseStoreInfo.getName());

            //1申请中，2代办中，3拒绝代办，4暂停代办，其他申请代办
            mTvBaseStoreApply.setText(baseStoreInfo.getAgentStateChs());
            mTvBaseStoreApply.setVisibility(View.VISIBLE);
            if (mTvBaseStoreApply.getText().toString().equals("解除中")) {
                mTvBaseStoreApply.setClickable(false);
            }
            mTvBaseStoreName.setVisibility(View.VISIBLE);
            mlyTab.setVisibility(View.VISIBLE);
        } else {
            mTvBaseStoreApply.setVisibility(View.GONE);
            mTvBaseStoreName.setVisibility(View.GONE);
        }

    }


    String TAG_BASE_STORE_INFO_FRAGMENT = "TAG_BASE_STORE_INFO_FRAGMENT";
    String TAG_BASE_STORE_WEB_FRAGMENT = "TAG_BASE_STORE_WEB_FRAGMENT";
    String TAG_BASE_STORE_PRODUCT_FRAGMENT = "TAG_BASE_STORE_PRODUCT_FRAGMENT";

    //0,商品，信息，1，首页，商品，信息
    int typeNav = 0;
    BaseStoreInfo mBaseStoreInfo;
    BaseStoreInfoFragment mBaseStoreInfoFragment;
    BaseStoreBaseWebFragment mBaseStoreBaseWebFragment;
    BaseStoreProductFragment mBaseStoreProductFragment;

    private void updatePageStatus(int i) {
        FragmentManager fm = getSupportFragmentManager();

        FragmentTransaction transaction = fm.beginTransaction();

        if (mBaseStoreBaseWebFragment != null) {
            transaction.hide(mBaseStoreBaseWebFragment);
        }
        if (mBaseStoreProductFragment != null) {
            transaction.hide(mBaseStoreProductFragment);
        }
        if (mBaseStoreInfoFragment != null) {
            transaction.hide(mBaseStoreInfoFragment);
        }

        if (typeNav == 0) {

            if (i == 0) {
                showProductInfoFragment(transaction);
            } else if (i == 1) {
                showBaseStoreInfoFragment(transaction);
            }
        } else if (typeNav == 1) {
            if (i == 0) {
                showBaseStoreWebFragment(transaction);
            } else if (i == 1) {
                showProductInfoFragment(transaction);
            } else if (i == 2) {
                showBaseStoreInfoFragment(transaction);
            }
        }
        transaction.commit();
    }


    private void showProductInfoFragment(FragmentTransaction transaction) {
        if (mBaseStoreProductFragment == null) {
            mBaseStoreProductFragment = new BaseStoreProductFragment();

            transaction.add(R.id.content, mBaseStoreProductFragment, TAG_BASE_STORE_PRODUCT_FRAGMENT);
        }
        mBaseStoreProductFragment.mBaseStoreId = mBaseStoreId;
        mBaseStoreProductFragment.mHasAgent = mHasAgent;
        transaction.show(mBaseStoreProductFragment);
    }

    private void showBaseStoreInfoFragment(FragmentTransaction transaction) {
        if (mBaseStoreInfoFragment == null) {
            mBaseStoreInfoFragment = new BaseStoreInfoFragment();

            transaction.add(R.id.content, mBaseStoreInfoFragment, TAG_BASE_STORE_INFO_FRAGMENT);
        }
        mBaseStoreInfoFragment.setBaseStoreInfo(mBaseStoreInfo);
        mBaseStoreInfoFragment.updateView(mBaseStoreInfo);
        transaction.show(mBaseStoreInfoFragment);
    }

    private void showBaseStoreWebFragment(FragmentTransaction transaction) {
        if (mBaseStoreBaseWebFragment == null) {
            mBaseStoreBaseWebFragment = new BaseStoreBaseWebFragment();

            transaction.add(R.id.content, mBaseStoreBaseWebFragment, TAG_BASE_STORE_WEB_FRAGMENT);
        }
        if (mBaseStoreInfo != null)
            mBaseStoreBaseWebFragment.url = mBaseStoreInfo.getHomepage();
        transaction.show(mBaseStoreBaseWebFragment);
    }


    void reqBaseStoreInfo() {
        //buy/store/base/info
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_BASE_INFO);
        RequestEntityMapSupply.putParameter("storeId", mBaseStoreId);//基地店铺ID
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());//批发商店铺ID
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_BASE_INFO, new OnRequestListener<BaseStoreInfo>() {
            @Override
            public BaseStoreInfo jsonToObj(String responseStr) {
                return JsonUtils.fromJson(responseStr, BaseStoreInfo.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<BaseStoreInfo> response, Object tag) {

                updateBaseStoreInfo(response.getResponseElement());
            }
        });
    }

}
